(function (win) {
  const
    tlog = async function (fn, d, isFirst, t) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          (fn || (function (msg, b) {
            b && ($('#olTaskLogs').html())
            $('#olTaskLogs').append(`<li>${msg}</li>`);
          }))(d, isFirst);
        }, t || 10);
      })
    };

  // // TODO:
  // fnPost = async function (act, d, ok, ng, ov) {
  //   await tlog(0, `Post ${act} begin`);
  //   // TODO:
  //   await tlog(0, `Post ${act} end`);
  // };

  // init
  $(function () {
    // init - event
    $$$.btnTry.click(function () {
      $.xhr({
        act: 'hasDir',
        ok: r => {
          $$$.lblTryResult.text($.toJSONS(r));
        }
      });
    });
    $$$.btnRefreshTasks.click(function () {
      $.xhr({
        act: 'getTasks',
        ok: r => {
          const hasTask = r.tasks.length > 0;
          hasTask ? ($$$.btnEditTask.show()) : ($$$.btnEditTask.hide());
          hasTask ? ($$$.btnDeleteTask.show()) : ($$$.btnDeleteTask.hide());
          $$$.tbTasks.replaceData(r.tasks);
        }
      });
    });
    $$$.btnAddTask.click(function () {
      $$$.fdsTaskAdd.show();
      $$$.btnAddTask.dis();
    });
    $$$.btnSaveTask.click(function () {
      !$$$.hidTaskID.val() && $$$.hidTaskID.val($.uuid());
      $.xhr({
        act: 'saveTask', d: $$$.fdsTaskAdd.formJSON(),
        ok: r => {
          if (r.r) { $.log(r.r); alert(r.r); return; }
          $$$.fdsTaskAdd.hide().formClear();
          $$$.btnAddTask.ena();
          $$$.btnRefreshTasks.click();
        }
      });
    });
    $$$.btnCancelTask.click(function () {
      $$$.txtTaskName.val('');
      $$$.fdsTaskAdd.hide();
      $$$.btnAddTask.ena();
    });

    $$$.btnEditTask.click(function () {
      $$$.fdsTaskAdd.jsonForm($$$.tbTasks.getSelectedData()[0]).show();
    });

    $$$.btnDeleteTask.click(function () {
      const ids = [];
      for (let it of $$$.tbTasks.getSelectedData()) { ids.push(it.taskID); }
      $.xhr({
        act: 'delTasks', d: { "taskIDs": ids },
        ok: r => {
          $$$.btnRefreshTasks.click();
        }
      });
    });

    // init - tbTasks
    $$$.tbTasks = new Tabulator("#tbTasks", {
      selectable: true,  // 点击行可选（与【点击checkbox行可选】不冲突）
      height: 300,
      index: "taskID",  // unique index value; should be either numeric or a string; By default field=id
      columns: [
        {  // 点击checkbox行可选（与【点击行可选】不冲突）
          formatter: "rowSelection", titleFormatter: "rowSelection", hozAlign: "center", headerSort: false, cellClick: function (e, cell) {
            cell.getRow().toggleSelect();
          }
        },
        { title: "Task ID", field: "taskID" },
        {
          title: "Task Name", field: "taskName",
          frozen: true  // 固定列设置
        },
        { title: "Task Detail", field: "taskDetail" }
      ]
      //TODO:
    });

    // init - tbTasks - Event:Row Selection Changed
    /**
     * @event tbTasks rowSelectionChanged
     * @summary init - tbTasks - Event:Row Selection Changed
     * @param {Array} data - array of data objects for the currently selected rows in order of selection
     * @param {Array} rows - array of row components for the currently selected rows in order of selection
     * @param {Array} selected - array of row components that were selected in the last action
     * @param {Array} deselected - array of row components that were deselected in the last action
     */
    $$$.tbTasks.on("rowSelectionChanged", function (data, rows, selected, deselected, btn) {
      (btn = $$$.btnEditTask) && (data.length === 1 ? btn.ena() : btn.dis());
      (btn = $$$.btnDeleteTask) && (data.length ? btn.ena() : btn.dis());
    });

    // init - final trigger
    $$$.btnRefreshTasks.click();
  });
})(window);